package com.dark.sharedLock;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.concurrent.TimeUnit;

/**
 * Created by tengxue on 16-6-12.
 */
public class BusinessTwo {
    private  static CuratorFramework client = CuratorFrameworkFactory.builder()
            .connectString("172.26.50.83:2181")
            .sessionTimeoutMs(5000)
            .connectionTimeoutMs(3000)
            .retryPolicy(new ExponentialBackoffRetry(1000, 3))
            .build();

    public static void  main(String[] args){
        client.getConnectionStateListenable().addListener(new ConnectionStateListener() {

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                System.out.println("** STATE CHANGED TO : " + newState);
                if (newState.equals(ConnectionState.LOST)){
                    client.close();
                }
            }
        });
        client.start();
        InterProcessSemaphoreMutex processSemaphoreMutex = new InterProcessSemaphoreMutex(client, "/test_group");
        try {
            boolean flag = processSemaphoreMutex.acquire(12, TimeUnit.MINUTES);
            if (flag){
                System.out.println("BusinessTwo Getting lock successful.");
                Thread.sleep(20 * 1000);
                System.out.println("------------------------the business is done.-------------------------------");
            }
            System.out.println("------------------------BusinessOne Getting lock failed.-------------------------------");


        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (processSemaphoreMutex.isAcquiredInThisProcess()){
                    processSemaphoreMutex.release();
                }
                client.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
